// 移动端答题逻辑

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// Toast提示
function showToast(message, duration = 2000) {
    const toast = document.createElement('div');
    toast.className = 'toast';
    toast.textContent = message;
    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'fadeOut 0.3s';
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// 全局变量
let questions = [];
let currentQuestionIndex = 0;
let userAnswers = [];
let fillInAnswers = []; // 填空题答案数组
let score = 0;
let timerInterval;
let startTime;
let selectedCategory = ''; // 空字符串表示全部分类

// 元素引用
const categorySelector = document.getElementById('categorySelector');
const quizArea = document.getElementById('quizArea');
const resultArea = document.getElementById('resultArea');
const startBtn = document.getElementById('startBtn');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const submitBtn = document.getElementById('submitBtn');

// 分类按钮事件
document.querySelectorAll('.category-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        document.querySelectorAll('.category-btn').forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        selectedCategory = btn.dataset.category;
    });
});

// 开始答题
startBtn.addEventListener('click', async () => {
    try {
        startBtn.disabled = true;
        startBtn.textContent = '加载中...';

        const response = await fetch(`/api/get-questions?category=${selectedCategory}&count=10`);
        const data = await response.json();

        if (data.success && data.questions && data.questions.length > 0) {
            questions = data.questions;
            userAnswers = new Array(questions.length).fill(null);
            fillInAnswers = new Array(questions.length).fill('');
            
            categorySelector.style.display = 'none';
            quizArea.style.display = 'block';
            
            // 显示固定答题按钮
            const navFixed = document.getElementById('quizNavigationFixed');
            if (navFixed) {
                navFixed.classList.add('active');
            }
            
            startTimer();
            loadQuestion();
        } else {
            showToast(data.message || '加载题目失败');
            startBtn.disabled = false;
            startBtn.textContent = '开始答题';
        }
    } catch (error) {
        console.error('加载题目错误:', error);
        showToast('网络错误，请重试');
        startBtn.disabled = false;
        startBtn.textContent = '开始答题';
    }
});

// 加载题目
function loadQuestion() {
    if (currentQuestionIndex >= questions.length) return;

    const question = questions[currentQuestionIndex];
    
    // 更新进度
    document.getElementById('currentQuestion').textContent = currentQuestionIndex + 1;
    document.getElementById('totalQuestions').textContent = questions.length;
    document.getElementById('scoreDisplay').textContent = score;
    
    const progress = ((currentQuestionIndex + 1) / questions.length) * 100;
    document.getElementById('progressFill').style.width = progress + '%';

    // 加载题目内容
    const questionTitleEl = document.getElementById('questionTitle');
    questionTitleEl.innerHTML = renderMarkdown(question.title);
    renderMath(questionTitleEl);

    // 加载题目图片
    const questionImageContainer = document.getElementById('questionImageContainer');
    const questionImage = document.getElementById('questionImage');
    if (question.question_image) {
        questionImage.src = question.question_image;
        questionImageContainer.style.display = 'block';
    } else {
        questionImageContainer.style.display = 'none';
    }

    // 根据题目类型加载不同的界面
    const optionsList = document.getElementById('optionsList');
    optionsList.innerHTML = '';
    
    if (question.question_type === 'fill_in_blank') {
        // 填空题界面
        const fillInContainer = document.createElement('div');
        fillInContainer.className = 'fill-in-container';
        
        const fillInLabel = document.createElement('div');
        fillInLabel.className = 'fill-in-label';
        fillInLabel.textContent = '请填写答案：';
        
        const fillInInput = document.createElement('input');
        fillInInput.type = 'text';
        fillInInput.className = 'fill-in-input';
        fillInInput.placeholder = '请输入您的答案...';
        fillInInput.id = 'fillInAnswer';
        
        // 恢复之前的填空答案
        if (fillInAnswers[currentQuestionIndex]) {
            fillInInput.value = fillInAnswers[currentQuestionIndex];
        }
        
        // 添加输入事件
        fillInInput.addEventListener('input', (e) => {
            fillInAnswers[currentQuestionIndex] = e.target.value;
            updateButtons();
        });
        
        fillInContainer.appendChild(fillInLabel);
        fillInContainer.appendChild(fillInInput);
        optionsList.appendChild(fillInContainer);
        
        // 聚焦到输入框
        setTimeout(() => fillInInput.focus(), 100);
    } else {
        // 选择题界面
        const labels = ['A', 'B', 'C', 'D'];
        question.options.forEach((option, index) => {
            const optionDiv = document.createElement('div');
            optionDiv.className = 'option-item';
            optionDiv.dataset.index = index;
            
            const optionLabel = document.createElement('div');
            optionLabel.className = 'option-label';
            optionLabel.textContent = labels[index];
            
            const optionText = document.createElement('div');
            optionText.className = 'option-text';
            
            // 检查选项是否是图片
            const optionImageKey = `option_${labels[index].toLowerCase()}_image`;
            if (question[optionImageKey]) {
                optionText.innerHTML = renderMarkdown(option || '');
                const img = document.createElement('img');
                img.src = question[optionImageKey];
                img.className = 'option-image';
                optionText.appendChild(img);
            } else {
                optionText.innerHTML = renderMarkdown(option);
            }
            
            renderMath(optionText);
            
            optionDiv.appendChild(optionLabel);
            optionDiv.appendChild(optionText);
            
            // 恢复之前的选择
            if (userAnswers[currentQuestionIndex] === index) {
                optionDiv.classList.add('selected');
            }
            
            // 添加点击事件
            optionDiv.addEventListener('click', () => selectOption(index));
            
            optionsList.appendChild(optionDiv);
        });
    }

    // 更新按钮状态
    updateButtons();
}

// 选择选项
function selectOption(index) {
    userAnswers[currentQuestionIndex] = index;
    
    // 更新UI
    document.querySelectorAll('.option-item').forEach((item, i) => {
        if (i === index) {
            item.classList.add('selected');
        } else {
            item.classList.remove('selected');
        }
    });
    
    updateButtons();
}

// 更新按钮状态
function updateButtons() {
    prevBtn.disabled = currentQuestionIndex === 0;
    
    const isLastQuestion = currentQuestionIndex === questions.length - 1;
    const currentQuestion = questions[currentQuestionIndex];
    
    // 根据题目类型检查是否有答案
    let hasAnswer = false;
    if (currentQuestion.question_type === 'fill_in_blank') {
        // 填空题检查fillInAnswers数组
        hasAnswer = fillInAnswers[currentQuestionIndex] && fillInAnswers[currentQuestionIndex].trim() !== '';
    } else {
        // 选择题检查userAnswers数组
        hasAnswer = userAnswers[currentQuestionIndex] !== null;
    }
    
    if (isLastQuestion) {
        nextBtn.style.display = 'none';
        submitBtn.style.display = 'block';
        submitBtn.disabled = !hasAnswer;
    } else {
        nextBtn.style.display = 'block';
        submitBtn.style.display = 'none';
        nextBtn.disabled = !hasAnswer;
    }
}

// 上一题
prevBtn.addEventListener('click', () => {
    if (currentQuestionIndex > 0) {
        currentQuestionIndex--;
        loadQuestion();
    }
});

// 下一题
nextBtn.addEventListener('click', () => {
    if (currentQuestionIndex < questions.length - 1) {
        currentQuestionIndex++;
        loadQuestion();
    }
});

// 提交答卷
submitBtn.addEventListener('click', () => {
    submitQuiz();
});

// 填空题答案检查函数
function checkFillInAnswer(userAnswer, correctAnswer, keywords = '') {
    if (!userAnswer || !correctAnswer) {
        return false;
    }
    
    // 清理用户答案
    userAnswer = userAnswer.trim().toLowerCase();
    
    // 处理多个正确答案（用逗号分隔）
    const correctAnswers = correctAnswer.split(',').map(ans => ans.trim().toLowerCase());
    
    // 处理关键词（用逗号分隔）
    const keywordList = keywords ? keywords.split(',').map(kw => kw.trim().toLowerCase()) : [];
    
    // 检查是否匹配正确答案
    if (correctAnswers.includes(userAnswer)) {
        return true;
    }
    
    // 检查是否匹配关键词
    if (keywordList.includes(userAnswer)) {
        return true;
    }
    
    // 模糊匹配（去除空格、标点符号）
    const userClean = userAnswer.replace(/[^\w\u4e00-\u9fff]/g, '');
    
    for (const ans of correctAnswers) {
        const ansClean = ans.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === ansClean) {
            return true;
        }
    }
    
    for (const kw of keywordList) {
        const kwClean = kw.replace(/[^\w\u4e00-\u9fff]/g, '');
        if (userClean === kwClean) {
            return true;
        }
    }
    
    return false;
}

// 提交答题
function submitQuiz() {
    stopTimer();
    
    // 隐藏固定答题按钮
    const navFixed = document.getElementById('quizNavigationFixed');
    if (navFixed) {
        navFixed.classList.remove('active');
    }
    
    // 计算成绩
    let correctCount = 0;
    let wrongCount = 0;
    
    questions.forEach((question, index) => {
        if (question.question_type === 'fill_in_blank') {
            // 填空题答案检查
            const userAnswer = fillInAnswers[index];
            if (checkFillInAnswer(userAnswer, question.fill_in_answer, question.fill_in_keywords)) {
                correctCount++;
            } else {
                wrongCount++;
            }
        } else {
            // 选择题答案检查
            const userAnswer = userAnswers[index];
            if (userAnswer === question.correct) {
                correctCount++;
            } else {
                wrongCount++;
            }
        }
    });
    
    score = correctCount * 10;
    const timeElapsed = Math.floor((Date.now() - startTime) / 1000);
    
    // 显示结果
    showResult(score, correctCount, wrongCount, timeElapsed);
    
    // 保存结果到服务器
    saveQuizResult({
        category: selectedCategory,
        correctCount: correctCount,
        wrongCount: wrongCount,
        score: score,
        timeElapsed: timeElapsed,
        questions: questions,
        userAnswers: userAnswers,
        fillInAnswers: fillInAnswers
    });
    
    // 保存到sessionStorage供详情页使用
    sessionStorage.setItem('quizResult', JSON.stringify({
        questions: questions,
        userAnswers: userAnswers,
        fillInAnswers: fillInAnswers,
        score: score,
        correctCount: correctCount,
        wrongCount: wrongCount,
        timeElapsed: timeElapsed
    }));
}

// 显示结果
function showResult(score, correctCount, wrongCount, timeElapsed) {
    quizArea.style.display = 'none';
    resultArea.style.display = 'block';
    
    document.getElementById('resultScore').textContent = score;
    document.getElementById('resultCorrect').textContent = correctCount;
    document.getElementById('resultWrong').textContent = wrongCount;
    document.getElementById('resultTime').textContent = formatTime(timeElapsed);
}

// 保存答题结果
async function saveQuizResult(data) {
    try {
        const response = await fetch('/api/save-quiz-result', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });
        
        const result = await response.json();
        if (!result.success) {
            console.warn('保存答题结果失败:', result.message);
        }
    } catch (error) {
        console.error('保存答题结果错误:', error);
    }
}

// 计时器
function startTimer() {
    startTime = Date.now();
    timerInterval = setInterval(() => {
        const elapsed = Math.floor((Date.now() - startTime) / 1000);
        document.getElementById('timerDisplay').textContent = formatTime(elapsed);
    }, 1000);
}

function stopTimer() {
    if (timerInterval) {
        clearInterval(timerInterval);
    }
}

function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 设置当前导航项为激活状态
function setActiveNav() {
    const path = window.location.pathname;
    document.querySelectorAll('.nav-item').forEach(item => {
        item.classList.remove('active');
        if (item.getAttribute('href') === path) {
            item.classList.add('active');
        }
    });
}

// 从URL参数获取分类并自动开始答题
function checkAutoStart() {
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category');
    const autostart = urlParams.get('autostart');
    
    if (autostart === '1') {
        // 设置选中的分类（空字符串表示全部题目）
        selectedCategory = category || '';
        
        // 查找并激活对应的分类按钮
        document.querySelectorAll('.category-btn').forEach(btn => {
            if (btn.dataset.category === selectedCategory) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
        
        // 立即隐藏分类选择器，显示加载状态
        categorySelector.style.display = 'none';
        quizArea.style.display = 'block';
        quizArea.innerHTML = '<div style="text-align: center; padding: 60px 20px; color: #667eea;"><div style="font-size: 48px; margin-bottom: 16px;">⏳</div><div style="font-size: 18px; font-weight: 600;">正在加载题目...</div></div>';
        
        // 自动加载题目并开始答题
        setTimeout(async () => {
            try {
                const response = await fetch(`/api/get-questions?category=${selectedCategory}&count=10`);
                const data = await response.json();

                if (data.success && data.questions && data.questions.length > 0) {
                    questions = data.questions;
                    userAnswers = new Array(questions.length).fill(null);
                    fillInAnswers = new Array(questions.length).fill('');
                    
                    // 恢复答题区域的原始HTML结构
                    restoreQuizAreaHTML();
                    
                    // 显示固定答题按钮
                    const navFixed = document.getElementById('quizNavigationFixed');
                    if (navFixed) {
                        navFixed.classList.add('active');
                    }
                    
                    startTimer();
                    loadQuestion();
                } else {
                    // 加载失败，显示错误并返回分类选择
                    categorySelector.style.display = 'block';
                    quizArea.style.display = 'none';
                    showToast(data.message || '加载题目失败，请重试');
                }
            } catch (error) {
                console.error('加载题目错误:', error);
                categorySelector.style.display = 'block';
                quizArea.style.display = 'none';
                showToast('网络错误，请重试');
            }
        }, 300);
    }
}

// 恢复答题区域的HTML结构
function restoreQuizAreaHTML() {
    quizArea.innerHTML = `
        <div class="quiz-header">
            <div class="progress-bar">
                <div class="progress-fill" id="progressFill" style="width: 0%"></div>
            </div>
            <div class="quiz-info">
                <span>题目 <span id="currentQuestion">1</span>/<span id="totalQuestions">10</span></span>
                <span>得分: <span id="scoreDisplay">0</span></span>
                <span>⏱️ <span id="timer">00:00</span></span>
            </div>
        </div>

        <div class="container">
            <div class="question-card">
                <div class="question-content">
                    <h3 class="question-title" id="questionTitle"></h3>
                    <div id="questionImageContainer" style="display: none;">
                        <img id="questionImage" class="question-image" alt="题目图片">
                    </div>
                </div>

                <div class="options-list" id="optionsList"></div>
            </div>

            <div class="action-buttons">
                <button class="btn btn-secondary" id="prevBtn" disabled>上一题</button>
                <button class="btn btn-primary" id="nextBtn">下一题</button>
                <button class="btn btn-success" id="submitBtn" style="display: none;">提交答卷</button>
            </div>
        </div>
    `;
    
    // 重新绑定按钮事件
    rebindQuizButtons();
}

// 重新绑定答题按钮事件
function rebindQuizButtons() {
    const newPrevBtn = document.getElementById('prevBtn');
    const newNextBtn = document.getElementById('nextBtn');
    const newSubmitBtn = document.getElementById('submitBtn');
    
    newPrevBtn.addEventListener('click', () => {
        if (currentQuestionIndex > 0) {
            currentQuestionIndex--;
            loadQuestion();
            updateNavigationButtons();
        }
    });
    
    newNextBtn.addEventListener('click', () => {
        if (currentQuestionIndex < questions.length - 1) {
            currentQuestionIndex++;
            loadQuestion();
            updateNavigationButtons();
        }
    });
    
    newSubmitBtn.addEventListener('click', submitQuiz);
}

// ========== AI助手功能 ==========
// AI助手相关元素
const aiAssistantBtn = document.getElementById('aiAssistantBtn');
const aiChatPanel = document.getElementById('aiChatPanel');
const aiCloseBtn = document.getElementById('aiCloseBtn');
const aiChatInput = document.getElementById('aiChatInput');
const aiSendBtn = document.getElementById('aiSendBtn');
const aiChatMessages = document.getElementById('aiChatMessages');

// AI助手按钮拖动功能（移动端）
if (aiAssistantBtn) {
    let isDragging = false;
    let startX, startY;
    let initialLeft, initialTop;
    
    // 确保按钮可见
    console.log('AI助手按钮初始化');
    aiAssistantBtn.style.display = 'flex';
    aiAssistantBtn.style.visibility = 'visible';
    aiAssistantBtn.style.opacity = '1';
    
    // 从localStorage加载保存的位置
    const savedPosition = localStorage.getItem('aiAssistantBtnPosition');
    if (savedPosition) {
        try {
            const { left, top } = JSON.parse(savedPosition);
            // 确保位置在屏幕内
            const maxLeft = window.innerWidth - 56;
            const maxTop = window.innerHeight - 56;
            const validLeft = Math.max(0, Math.min(parseInt(left), maxLeft));
            const validTop = Math.max(0, Math.min(parseInt(top), maxTop));
            
            aiAssistantBtn.style.left = validLeft + 'px';
            aiAssistantBtn.style.top = validTop + 'px';
            aiAssistantBtn.style.right = 'auto';
            aiAssistantBtn.style.bottom = 'auto';
            console.log('加载保存的位置:', validLeft, validTop);
        } catch (e) {
            console.error('加载位置失败:', e);
            // 如果加载失败，清除缓存
            localStorage.removeItem('aiAssistantBtnPosition');
        }
    }
    
    // 触摸开始
    aiAssistantBtn.addEventListener('touchstart', function(e) {
        isDragging = false;
        aiAssistantBtn.classList.add('dragging');
        
        const touch = e.touches[0];
        const rect = aiAssistantBtn.getBoundingClientRect();
        startX = touch.clientX;
        startY = touch.clientY;
        initialLeft = rect.left;
        initialTop = rect.top;
        
        e.stopPropagation();
    }, { passive: true });
    
    // 触摸移动
    aiAssistantBtn.addEventListener('touchmove', function(e) {
        if (!aiAssistantBtn.classList.contains('dragging')) return;
        
        const touch = e.touches[0];
        const deltaX = touch.clientX - startX;
        const deltaY = touch.clientY - startY;
        
        // 如果移动距离超过5px，才认为是拖动
        if (Math.abs(deltaX) > 5 || Math.abs(deltaY) > 5) {
            isDragging = true;
            e.preventDefault(); // 防止滚动
        }
        
        if (isDragging) {
            let newLeft = initialLeft + deltaX;
            let newTop = initialTop + deltaY;
            
            // 边界限制
            const btnWidth = aiAssistantBtn.offsetWidth;
            const btnHeight = aiAssistantBtn.offsetHeight;
            newLeft = Math.max(0, Math.min(newLeft, window.innerWidth - btnWidth));
            newTop = Math.max(0, Math.min(newTop, window.innerHeight - btnHeight));
            
            aiAssistantBtn.style.left = newLeft + 'px';
            aiAssistantBtn.style.top = newTop + 'px';
            aiAssistantBtn.style.right = 'auto';
            aiAssistantBtn.style.bottom = 'auto';
        }
    }, { passive: false });
    
    // 触摸结束
    aiAssistantBtn.addEventListener('touchend', function() {
        if (aiAssistantBtn.classList.contains('dragging')) {
            aiAssistantBtn.classList.remove('dragging');
            
            // 保存位置
            if (isDragging) {
                const position = {
                    left: aiAssistantBtn.style.left,
                    top: aiAssistantBtn.style.top
                };
                localStorage.setItem('aiAssistantBtnPosition', JSON.stringify(position));
            } else {
                // 如果没有拖动，则是点击事件，直接打开对话框
                aiChatPanel.classList.toggle('active');
                if (aiChatPanel.classList.contains('active')) {
                    // 延迟聚焦，避免键盘弹出时界面闪烁
                    setTimeout(() => {
                        aiChatInput.focus();
                    }, 300);
                }
            }
            
            isDragging = false;
        }
    });
}

// 关闭AI助手面板
if (aiCloseBtn) {
    aiCloseBtn.addEventListener('click', function() {
        aiChatPanel.classList.remove('active');
    });
}

// 发送消息
if (aiSendBtn) {
    aiSendBtn.addEventListener('click', sendAIMessage);
}

// 回车发送（Shift+Enter换行）
if (aiChatInput) {
    aiChatInput.addEventListener('keydown', function(e) {
        if (e.key === 'Enter' && !e.shiftKey) {
            e.preventDefault();
            sendAIMessage();
        }
    });
}

// 发送AI消息（流式输出）
async function sendAIMessage() {
    const message = aiChatInput.value.trim();
    if (!message) return;
    
    // 显示用户消息
    addAIMessage(message, 'user');
    aiChatInput.value = '';
    
    // 禁用发送按钮
    aiSendBtn.disabled = true;
    aiSendBtn.innerHTML = '<span class="ai-loading">思考中</span>';
    
    // 创建AI消息容器
    const aiMessageDiv = document.createElement('div');
    aiMessageDiv.className = 'ai-message ai-message-assistant';
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'ai-message-content explanation-text';
    contentDiv.textContent = '';
    
    aiMessageDiv.appendChild(contentDiv);
    aiChatMessages.appendChild(aiMessageDiv);
    
    // 用于累积markdown内容
    let markdownContent = '';
    
    // 渲染markdown内容的函数
    function renderMarkdown(content) {
        if (typeof marked !== 'undefined') {
            try {
                // 使用marked.js渲染markdown
                const html = marked.parse(content);
                contentDiv.innerHTML = html;
                
                // 渲染数学公式（KaTeX）- 使用防抖避免重复渲染
                if (typeof renderMathInElement !== 'undefined') {
                    // 清除之前的渲染定时器
                    if (window.mobileLatexRenderTimer) {
                        clearTimeout(window.mobileLatexRenderTimer);
                    }
                    
                    // 延迟渲染，避免流式输出中的频繁重复渲染
                    window.mobileLatexRenderTimer = setTimeout(() => {
                        try {
                            console.log('移动端流式渲染LaTeX公式...');
                            renderMathInElement(contentDiv, {
                                delimiters: [
                                    {left: '$$', right: '$$', display: true},
                                    {left: '$', right: '$', display: false},
                                    {left: '\\[', right: '\\]', display: true},
                                    {left: '\\(', right: '\\)', display: false}
                                ],
                                throwOnError: false,
                                errorColor: '#cc0000'
                            });
                            console.log('移动端流式LaTeX渲染完成');
                        } catch (e) {
                            console.error('移动端流式LaTeX渲染错误:', e);
                        }
                    }, 100); // 100ms延迟，等待流式输出稳定
                } else {
                    console.warn('移动端流式KaTeX renderMathInElement 函数未找到');
                }
            } catch (e) {
                console.error('Markdown渲染错误:', e);
                contentDiv.textContent = content;
            }
        } else {
            // 如果没有marked.js，使用纯文本
            contentDiv.textContent = content;
        }
    }
    
    try {
        // 获取选择的AI服务
        const aiService = document.getElementById('aiServiceSelector').value;
        
        const response = await fetch('/api/ai/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ 
                message: message,
                service: aiService 
            })
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        // 读取流式响应
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        
        while (true) {
            const { done, value } = await reader.read();
            
            if (done) break;
            
            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split('\n');
            buffer = lines.pop() || ''; // 保留不完整的行
            
            for (const line of lines) {
                if (line.startsWith('data: ')) {
                    const data = line.slice(6);
                    if (data === '[DONE]') {
                        break;
                    }
                    
                    try {
                        const parsed = JSON.parse(data);
                        if (parsed.content) {
                            markdownContent += parsed.content;
                            // 实时渲染markdown
                            renderMarkdown(markdownContent);
                            // 滚动到底部
                            aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
                        } else if (parsed.error) {
                            contentDiv.textContent = '抱歉，AI服务暂时不可用：' + parsed.error;
                        }
                    } catch (e) {
                        console.error('解析流数据错误:', e);
                    }
                }
            }
        }
        
        // 如果没有内容，显示错误
        if (!markdownContent.trim()) {
            contentDiv.textContent = '抱歉，我现在无法回答。请稍后再试。';
        } else {
            // 最后再渲染一次，确保完整显示
            renderMarkdown(markdownContent);
        }
        
    } catch (error) {
        console.error('AI对话错误:', error);
        contentDiv.textContent = '网络错误，请检查连接后重试。';
    } finally {
        // 恢复发送按钮
        aiSendBtn.disabled = false;
        aiSendBtn.textContent = '发送';
    }
}

// 添加消息到对话框
function addAIMessage(content, role) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `ai-message ai-message-${role}`;
    
    const contentDiv = document.createElement('div');
    contentDiv.className = 'ai-message-content' + (role === 'assistant' ? ' explanation-text' : '');
    
    // 如果是AI助手消息，使用markdown渲染；用户消息保持纯文本
    if (role === 'assistant' && typeof marked !== 'undefined') {
        contentDiv.innerHTML = marked.parse(content);
        // 渲染数学公式
        if (typeof renderMathInElement !== 'undefined') {
            try {
                console.log('移动端正在渲染LaTeX公式...');
                renderMathInElement(contentDiv, {
                    delimiters: [
                        {left: '$$', right: '$$', display: true},
                        {left: '$', right: '$', display: false},
                        {left: '\\[', right: '\\]', display: true},
                        {left: '\\(', right: '\\)', display: false}
                    ],
                    throwOnError: false,
                    errorColor: '#cc0000'
                });
                console.log('移动端LaTeX公式渲染完成');
            } catch (e) {
                console.error('移动端LaTeX渲染错误:', e);
            }
        } else {
            console.warn('移动端KaTeX renderMathInElement 函数未找到');
        }
    } else {
        contentDiv.textContent = content;
    }
    
    messageDiv.appendChild(contentDiv);
    aiChatMessages.appendChild(messageDiv);
    
    // 滚动到底部
    aiChatMessages.scrollTop = aiChatMessages.scrollHeight;
}

setActiveNav();
checkAutoStart();

